/**
 * watch_dog.c
 *
 *  Created on: 2018-03-09
 *      Author: chenshisheng
 */

#include "watch_dog.h"
#include "ctimer.h"

//#define IWDGx IWDG

// 看门狗超时时长（秒）
#define WATCH_DOG_TIME_OUT 3

// 看门狗所需reload的定时时间间隔（秒）
#define WATCH_DOG_RELOAD_TIMING 2

static Ctimer_t _timer;

static int _OnTimeout(void *argument)
{
	UNUSED(argument);

    SYS_UnlockReg();;
    WDT_RESET_COUNTER();
    SYS_LockReg();
	return 0;
}

void WatchDog_Init(void)
{
    /* Check if the system has resumed from IWDG reset */
    if(SYS_IS_WDT_RST())
    {
      nbprintf("Watch Dog Reset!\n");
    }
    else if(SYS_IS_SYSTEM_RST())
    {
        nbprintf("Software Reset\n");
    }
    else if(SYS_IS_RSTPIN_RST())
    {
        nbprintf("NRST Pin Reset!\n");
    }

    SYS_UnlockReg();;
    // WDT timeout freq = 10kHz / 2^14 = 0.6103515625Hz
    WDT_Open(WDT_TIMEOUT_2POW16, WDT_RESET_DELAY_18CLK, TRUE, TRUE);
    SYS_LockReg();

    WDT_RESET_COUNTER();
    Ctimer_Start(&_timer, CTIMER_TICK_SECOND(WATCH_DOG_RELOAD_TIMING), _OnTimeout, 0, NULL);
}
